package org.lex.swing.graph;

import javax.swing.event.EventListenerList;

public abstract class AbstractProgressModel implements ProgressModel {
	private EventListenerList listeners = new EventListenerList();
	private long max = 100L;

	@Override
	public long getMaximum() {
		return max;
	}

	@Override
	public void setMaximum(long max) {
		if (max != this.max && max > 0) {
			this.max = max;
			this.fireBoundsChanged();
		}
	}

	@Override
	public void addRange(long from, long to) {
		this.addRange(new Range(from, to));
	}

	@Override
	public void removeRange(long from, long to) {
		this.removeRange(new Range(from, to));
	}

	@Override
	public void removeAll() {
		this.removeRange(0, this.getMaximum());
	}

	@Override
	public void addGraphListener(ProgressListener l) {
		this.listeners.add(ProgressListener.class, l);
	}

	@Override
	public void removeGraphListener(ProgressListener l) {
		this.listeners.remove(ProgressListener.class, l);
	}

	protected void fireRangesAdded(Range... ranges) {
		Object[] lists = listeners.getListenerList();
		for (int i = lists.length - 2; i >= 0; i -= 2) {
			if (lists[i] == ProgressListener.class) {
				((ProgressListener) lists[i + 1]).rangesAdded(new ProgressEvent(this, ranges));
			}
		}
	}

	protected void fireRangesRemoved(Range... ranges) {
		Object[] lists = listeners.getListenerList();
		for (int i = lists.length - 2; i >= 0; i -= 2) {
			if (lists[i] == ProgressListener.class) {
				((ProgressListener) lists[i + 1]).rangesRemoved(new ProgressEvent(this, ranges));
			}
		}
	}

	private final ProgressEvent BOUNDS_CHANGED = new ProgressEvent(this, new Range[0]);

	protected void fireBoundsChanged() {
		Object[] lists = listeners.getListenerList();
		for (int i = lists.length - 2; i >= 0; i -= 2) {
			if (lists[i] == ProgressListener.class) {
				((ProgressListener) lists[i + 1]).boundsChanged(BOUNDS_CHANGED);
			}
		}
	}
}
